<#import "../tpl/pageTep.ftl" as page>
<@page.pageBase currentMenu="活动管理">
<style>
    .button-large {
        font-size: 16px;
    }

    hr {
        border-color: #009688;
    }

    .webuploader-pick {
        background: none;
        padding: 0;
    }
</style>
<div class="xm-offline">
    <div class="row">
        <div class="panel">
            <div class="panel-header">
                <a href="/rest/manage/activity/toList">返回上一级</a>
            </div>
            <div class="panel-body">
            <#--form表单提交，相当于data-->
                <form id="editForm" class="form-horizontal" action="${basepath}/rest/manage/activity/updateActivityJson"
                      method="post">
                    <input type="hidden" class="control-text span-width span10" name="id" value="${e.id!}">

                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            活动名称：
                        </label>

                        <div class="controls">
                            <input type="text" data-rules="{required:true}" class="control-text span-width span8"
                                   name="kaName" value="${e.kaName!}" placeholder="请输入活动名称"/>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            品牌商：
                        </label>

                        <div class="controls" id="brandSelect">
                            <input type="hidden" id="brand" name="brandID" value="${e.brandID!}"/>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            活动要求：
                        </label>

                        <div class="controls  control-row-auto">
                            <textarea class="control-row4 input-large" name="demand" id="content"
                                      value="${e.kaDemand!}"></textarea>

                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            开始日期：
                        </label>

                        <div class="controls">
                            <input type="text" style="width: 140px;" name="kaStarTime"
                                   data-rules="{required : true,sid:只能取往后一天的日期}" data-messages="{required:'只能取往后一天的日期'}"
                                   id="beginTime" class="calendar offline-starTime" placeholder="请选择活动开始日期"
                                   value="${e.kaStarTime!}"
                                    />
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            结束日期：
                        </label>

                        <div class="controls">
                            <input type="text" style="width: 140px;" class="calendar time offline-endTime "
                                   name="kaEndTime"
                                   data-rules="{required : true}" placeholder="请选择活动结束日期" id="kaEndTime"
                                   value="${e.kaEndTime!}"/>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            活动预算：
                        </label>

                        <div class="controls">
                            <input type="text" data-rules="{required:true}" class="control-text span-width span8"
                                   name="kaBudge" placeholder="请输入活动预算" value="${e.kaBudge!}"/>
                        </div>
                    </div>
                    <h3 class="offset2">活动图片
                        <a class="button button-primary pull-right" id="imagesBtn" style="height:16px;">上传图片</a>
                    </h3>
                    <hr>
                    <input type="hidden" class="control-text span-width " name="kaPicture" id="picture"
                           data-rules="{required:true}"
                           value="${e.kaPicture!}">

                    <div id="imagesGrid" class="xm-grid">
                    </div>
                    <h3 class="offset2">商品信息
                        <a class="button button-primary pull-right" style="height:16px;" href="javascript:addProduct()">添加</a>
                    </h3>
                    <hr>
                    <input type="hidden" class="picture1 control-text span-width " name="kaProductName"
                           data-rules="{required:true}" id="kaProductName1" value="${e.kaProductName!}">
                    <input type="hidden" class="picture1 control-text span-width " name="kaProductCode"
                           id="kaProductCode1" value="${e.kaProductCode!}">

                    <div id="productGrid" class="xm-grid">
                    </div>
                    <div class="centered">
                        <a class="button  button-large  button-success" id="saveBtn">保存</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<#-----------------------------------------------添加商品信息的弹出框------------------------------------------->
<div id="addSpecContent" style="display:none;">
    <form id="addSpecForm" class="form-horizontal">
        <div class="row">
            <div class="control-group">
                <label class="control-label">商品名称：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" id="addName"
                           data-rules="{required : true}" name="kaProductName"/>
                </div>
            </div>
            <div class="control-group">
                <label class="control-label">条形码：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" id="addCode"
                           data-rules="{required : true}" name="kaProductCode" readonly/>
                    <a id="addImgBtn" class="button button-min button-primary pull-right"
                       style="height:20px;margin-left: 10px;">上传</a>
                </div>
            </div>
        </div>
    </form>
</div>
<#-----------------------------------------------添加商品信息的弹出框------------------------------------------->
<#-----------------------------------------------编辑商品规格start------------------------------------------->
<div id="editProductContent" style="display:none;">
    <form id="editProductForm" class="form-horizontal">
        <div class="row">
            <div class="control-group span16">
                <label class="control-label">商品名称：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" id="editName" name="kaProductName"
                           data-rules="{required : true}">
                </div>
            </div>
            <div class="control-group span16">
                <label class="control-label">条形码：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" id="editCode"
                           data-rules="{required : true}" name="kaProductCode" readonly/>
                    <a id="editImgBtn" class="button button-min button-primary pull-right"
                       style="height:20px;margin-left: 10px;">上传</a>
                </div>
            </div>
        </div>
    </form>
</div>
<#-----------------------------------------------编辑商品规格end------------------------------------------->
<script type="text/javascript">
    var Grid = BUI.Grid;
    var Store = BUI.Data.Store;
    var Data = BUI.Data;
    var Select = BUI.Select;
    var imagesStore = new Store({});
    var editForm = new BUI.Form.Form({
        srcNode: '#editForm',
        submitType: 'ajax',
        callback: function (data) {
            if (data.success == true) {
                window.location.href = '/rest/manage/activity/toList';
            } else {
                BUI.Message.Alert(data.message, 'error');
                return;
            }
        }
    }).render();

    //点击保存按钮，判断
    $("#saveBtn").click(function () {
        var starTime = $(".offline-starTime").val(),
                endTime = $(".offline-endTime").val();
        if (editForm.isValid()) {
            if (starTime > endTime) {
                //结束日期要大于开始日期
                BUI.Message.Alert('结束日期要大于开始日期', function () {
                }, 'info');
            }
            else {
                editForm.ajaxSubmit();
            }
        } else {
            editForm.valid();
        }
    });

    //品牌商下拉查询
    var brandStore = new Data.Store({
        url: '/rest/manage/account/selectAllBrand',
        autoLoad: true,
        root: 'data'
    });
    var brandSelect = new Select.Select({
        render: '#brandSelect',
        valueField: '#brand',
        list: {
            itemTpl: '<li>{nickname}</li>',
            idField: 'id',
            elCls: 'bui-select-list'
        },
        store: brandStore
    }).render();
    /*--------------------------产品规格列表  begin--------------------*/
    /**
     * 规格信息
     * @type {*[]}
     */

    var specColumns = [
        {
            title: '商品名称', dataIndex: 'kaProductName', elCls: "center"

        },
        {
            title: '条形码', dataIndex: 'kaProductCode', elCls: "center", renderer: function (data) {
            return '<img src="${basepath}/' + data + '" width="100px" height="100px"/>';

        }
        },
        {
            title: '操作', dataIndex: 'id', elCls: "center", renderer: function (data, obj, index) {
            return '<a href="javascript:editProduct(' + data + ')">编辑</a><a href="javascript:delProduct(' + data + ')" style="margin-left:10px;">删除</a>';
        }
        }
    ];
    var specStore = new Store({});
    var specGrid = new Grid.Grid({
        render: '#productGrid',
        columns: specColumns,
        forceFit: true,
        loadMask: true, //加载数据时显示屏蔽层
        store: specStore
    }).render();
    /**
     * 初始化商品信息列表数据源
     * */
    function productStore() {
        var productNameArr = "${e.kaProductName!}".split(',');
        var productCodeArr = "${e.kaProductCode!}".split(',');
        for (var j = 0; j < productCodeArr.length; j++) {
            var obj = new Object();
            obj.id=j;
            obj.kaProductCode = productCodeArr[j];
            obj.kaProductName = productNameArr[j];
            specStore.add(obj);
        }
    }
    productStore();
    /**
     * 删除缓存商品信息
     * @param index
     */
    function delProduct(index) {
        //remove行数
        var record = specStore.find('id',index);
        specStore.remove(record);
        var imgStr = specStore.getResult();
        var imgArr = new Array();
        var nameArr = new Array();
        for (var i = 0; i < imgStr.length; i++) {
            imgArr[i] = imgStr[i].kaProductCode;
            nameArr[i] = imgStr[i].kaProductName;
        }
        $("#kaProductCode1").val(imgArr.join(","));
        $("#kaProductName1").val(nameArr.join(","));
    }

    /*--------------------------产品规格列表  end---------------------------*/
    /*----------------------------------------------新增表单处理 begin------------------------------------*/
    var addSpecForm = new BUI.Form.Form({
        srcNode: '#addSpecForm',
        submitType: 'ajax',
        callback: function (data) {
            var obj = new Object();
            obj.start = 0; //返回第一页
            store.load(obj);
            addSpecForm.close();
        }
    }).render();
    var addProductDialog = new BUI.Overlay.Dialog({
        title: '新增商品信息',
        width: 500,
        height: 200,
        contentId: 'addSpecContent',
        success: function () {
            this.close();
            if (addSpecForm.isValid()) {
                var stores=specStore.getResult();
                var obj = new Object();
                var i=0;
                if(stores==null||stores==""){
                    obj.id=i;
                }else{
                    obj.id=stores[stores.length-1].id+1;
                }
                obj.kaProductCode = $('#addCode').val();
                obj.kaProductName = $('#addName').val();
                specStore.add(obj);
                var addName = $('#addName').val();
                var addCode = $('#addCode').val();
                var inputName = $("#kaProductName1").val();
                var inputCode = $("#kaProductCode1").val();
                if(inputName!=""&&inputCode!=""){
                    $("#kaProductName1").val(inputName + ',' + addName);
                    $("#kaProductCode1").val(inputCode + ',' + addCode);
                }else{
                    $("#kaProductName1").val(addName);
                    $("#kaProductCode1").val(addCode);
                }
            } else {
                addSpecForm.valid();
            }
        }
    });
    /**
     *规格新增按钮事件
     */
    function addProduct() {
        $('#addName').val("");
        $('#addCode').val("");
        addSpecForm.clearErrors();//清楚第一次填写的内容
        addProductDialog.show();
        var addUploader = WebUploader.create({
            auto: true,
            swf: '${staticpath}/ueditor/third-party/webuploader/Uploader.swf',
            server: '${basepath}/rest/manage/ued/config?action=uploadimage',
            pick: '#addImgBtn',
            resize: false,
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png,'
            }
        });
        addUploader.on('uploadSuccess', function (file, response) {
            addUploader.removeFile(file);
            addSpecForm.setFieldValue("kaProductCode", response.url)
        });
    }

    /*----------------------------------------------新增表单处理 end------------------------------------*/
    /*------------------------------------------------编辑表单处理 start-----------------------------------------------*/
    var editProductForm = new BUI.Form.Form({
        srcNode: '#editProductForm',
        submitType: 'ajax',
        callback: function (data) {
            var obj = new Object();
            obj.start = 0; //返回第一页
            store.load(obj);
            editDialog.close();
        }
    });
    editProductForm.render();
    //编辑按钮事件
    var editRecord = new Object();
    function editProduct(index) {
        editRecord = specStore.find('id',index);
        editDialog.show();
        $('#editName').val(editRecord.kaProductName);
        $('#editCode').val( editRecord.kaProductCode);
        var editUploader = WebUploader.create({
            auto: true,
            swf: '${staticpath}/ueditor/third-party/webuploader/Uploader.swf',
            server: '${basepath}/rest/manage/ued/config?action=uploadimage',
            pick: '#editImgBtn',
            resize: false,
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png,'
            }
        });
        editUploader.on('uploadSuccess', function (file, response) {
            editUploader.removeFile(file);
            editProductForm.setFieldValue("kaProductCode", response.url)
        });
    }
    var editDialog = new BUI.Overlay.Dialog({
        title: '编辑商品信息',
        width: 500,
        height: 200,
        contentId: 'editProductContent',
        success: function () {
            this.close();
            if (editProductForm.isValid()) {
                editRecord.kaProductName = $('#editName').val();
                editRecord.kaProductCode = $('#editCode').val();
                specStore.update(editRecord);
                var productStr = specStore.getResult();
                var editName='';
                var editCode='';
                for (var i = 0; i < productStr.length; i++) {
                    editName=editName+','+productStr[i].kaProductName;
                    editCode=editCode+','+productStr[i].kaProductCode;
                }
                $("#kaProductCode1").val(editCode.substr(1));
                $("#kaProductName1").val(editName.substr(1));

            } else {
                editProductForm.valid();
            }
        }
    });

    /*------------------------------------------------编辑表单处理 end------------------------------------------------*/
    /*--------------------------活动图片列表  begin--------------------*/
    /**
     * 图片信息
     * @type {*[]}
     */
    var imagesColumns = [
        {
            title: '图片', dataIndex: 'url', width: '30%', renderer: function (data) {
            return '<img src="${basepath}/' + data + '" width="100px" height="100px"/>'
        }
        },
        {
            title: '状态', dataIndex: 'state', width: '30%', renderer: function (data) {
            if (data == "SUCCESS") {
                return "上传成功";
            }
            return "上传失败";
        }
        },
        {
            title: '操作', dataIndex: 'title', width: '40%', renderer: function (data, obj, index) {
            return '<a href="javascript:delImages(' + index + ')">删除</a>';
        }
        }
    ];
    /**
     * 删除缓存图片信息
     * @param index
     */
    function delImages(index) {
        var record = imagesStore.findByIndex(index);
        imagesStore.remove(record);
        var imgStr = imagesStore.getResult();
        var imgArr = new Array();
        for (var i = 0; i < imgStr.length; i++) {
            imgArr[i] = imgStr[i].url
        }
        $("#picture").val(imgArr.join(","));
    }
    /**
     * 初始化图片列表数据源
     * */
    function initImagesStore() {
        var imgArr = $("#picture").val().split(',');
        for (var i = 0; i < imgArr.length; i++) {
            var obj = new Object();
            obj.url = imgArr[i];
            obj.state = "SUCCESS";
            imagesStore.add(obj);
        }
    }
    initImagesStore();

    var imagesGrid = new Grid.Grid({
        render: '#imagesGrid',
        width: '100%',//如果表格使用百分比，这个属性一定要设置
        columns: imagesColumns,
        idField: 'title',
        store: imagesStore
    }).render();
    /*--------------------------活动图片列表  end--------------------*/

    /*------------------------图片上传插件配置  begin-----------------------*/
    var uploader = WebUploader.create({
        auto: true,
        swf: '${staticpath}/ueditor/third-party/webuploader/Uploader.swf',
        server: '${basepath}/rest/manage/ued/config?action=uploadimage',
        pick: '#imagesBtn',
        resize: false,
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png,'
        }
    });

    uploader.on('uploadSuccess', function (file, response) {
        uploader.removeFile(file);
        imagesStore.add(response);
        var imgStr = imagesStore.getResult();
        var imgArr = new Array();
        for (var i = 0; i < imgStr.length; i++) {
            imgArr[i] = imgStr[i].url
        }
        $("#picture").val(imgArr.join(","));
    });
    /*------------------------图片上传插件配置  end-----------------------*/
</script>

</@page.pageBase>